package com.fortune.rainshine.controller;

import com.fortune.rainshine.feign.common.RedisFeign;
import com.fortune.rainshine.feign.common.SmsSendFeign;
import com.fortune.rainshine.feign.service.ProductSaleFeign;
import com.fortune.rainshine.feign.service.ShopFeign;
import com.fortune.rainshine.feign.system.CustomerFeign;
import com.fortune.rainshine.feign.system.UserFeign;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.enums.RedisConstantEnum;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.CustomerModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.SmsParamsModel;
import com.fortune.rainshinecommon.model.service.StockRecordsModel;
import com.fortune.rainshinecommon.model.system.CustomerCardModel;
import com.fortune.rainshinecommon.util.RandomNumUtil;
import com.google.gson.Gson;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: rainShine
 * @description:
 * @author: tangyn
 * @create: 2019-05-24
 **/
@RestController
@RequestMapping("productSaleController")
public class ProductSaleController {
    private static final Logger logger = LoggerFactory.getLogger(ProductSaleController.class);
    @Autowired
    private CustomerFeign customerFeign;
    @Autowired
    private RedisFeign redisFeign;
    @Autowired
    private ProductSaleFeign productSaleFeign;
    @Autowired
    private SmsSendFeign smsSendFeign;
    @Value("${smsSend.number}")
    private Integer number;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private ShopFeign shopFeign;

    @RequiresPermissions("productSale:sms")
    @ResponseBody
    @RequestMapping("/sms")
    public MsgModel sms(@RequestBody CustomerCardModel customerCard) {
        try {
            CustomerModel customer = customerFeign.getCustomer(customerCard.getCustomerId());
            String phone = customer.getCustomerPhone();
            Boolean exists = redisFeign.exists(RedisConstantEnum.BUYPRODUCT.getMessage() + phone);
            if (exists) {
                redisFeign.delete(RedisConstantEnum.BUYPRODUCT.getMessage() + phone);
            }
            Gson gson = new Gson();
            String code = RandomNumUtil.getRandNum(number);
            SmsParamsModel smsParams = new SmsParamsModel();
            smsParams.setCode(code);
            String jsonParams = gson.toJson(smsParams);

            Boolean bo = smsSendFeign.sendSms(phone, jsonParams);
            if (bo) {
                redisFeign.set(RedisConstantEnum.BUYPRODUCT.getMessage() + phone, code, 60000);
            }
            return new MsgModel(ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("sms =====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @RequiresPermissions("productSale:add")
    @ResponseBody
    @RequestMapping("/add")
    public MsgModel add(@RequestBody StockRecordsModel model) {
        try {
            //判断用户是否存在
            CustomerModel customer = customerFeign.getCustomer(model.getCustomerId());
            if (customer != null) {
                //redis key
                String key = RedisConstantEnum.BUYPRODUCT.getMessage() + customer.getCustomerPhone();
                //判断是否存在于redis中
                Boolean exists = redisFeign.exists(key);
                if (exists) {
                    //获取redis中的keyc
                    String sms = (String) redisFeign.get(key).getData();
                    if (sms.equals(model.getVerificationCode())) {
                        //model.setUser(this.getLoginUser());
                        MsgModel msg = productSaleFeign.saleOrUse(model);
                        redisFeign.delete(key);
                        return msg;
                    } else {
                        return new MsgModel("验证码不正确", ResultCode.FAILURE);
                    }
                } else {
                    return new MsgModel("验证码不存在或者已过期", ResultCode.FAILURE);
                }
            } else {
                return new MsgModel("用户不存在", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("add ======> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }

    }

    @RequiresPermissions("productSale:use")
    @ResponseBody
    @RequestMapping("/use")
    public MsgModel use(@RequestBody StockRecordsModel model) {
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String userId = request.getHeader("userId");
        try {
            //model.setUser(this.getLoginUser());
            //model.setCreateId(this.getLoginUser().getUserId());
//            model.setCreateId(model.getUserId());
            model.setCreateId(Integer.valueOf(userId));
            return productSaleFeign.saleOrUse(model);
        } catch (Exception e) {
            logger.error("use =====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @ResponseBody
    @RequestMapping("/list")
    public MsgModel list(@RequestBody ParmsModel parm){
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String userId = request.getHeader("userId");
        try {
            if(parm.getShopId() == null || parm.getType() == null){
                return new MsgModel("参数异常", ResultCode.FAILURE);
            }
            ShopModel shopModel = shopFeign.getShopByShopId(parm.getShopId());
            if(shopModel == null){
                return new MsgModel("商铺参数异常", ResultCode.FAILURE);
            }
            Integer roleId = userFeign.getRoleIdByUserId(Integer.valueOf(userId));
            if(shopModel.getManagerId() != Integer.valueOf(userId) && roleId != 2){
                return new MsgModel("无操作权限", ResultCode.FAILURE);
            }

            if (parm.getPage() == null) {
                parm.setPage(1);
                parm.setLimit(10);
            }
            return productSaleFeign.list(parm);
        } catch (Exception e){
            logger.error("productSaleController ====> {}", e);
            return new MsgModel("获取记录异常", ResultCode.FAILURE);
        }
    }

}
